import os
import sys
import time
from loguru import logger
from typing import Optional
from contextvars import ContextVar

basedir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
log_path = os.path.join(basedir, 'logs')
if not os.path.exists(log_path):
    os.mkdir(log_path)

log_file = os.path.join(log_path, f'devops.log')

x_trace_id: ContextVar[Optional[str]] = ContextVar('x_trace_id', default="")
celery_task_id: ContextVar[Optional[str]] = ContextVar('celery_task_id', default="")


def correlation_id_filter(record):
    record['x_trace_id'] = x_trace_id.get()
    record['celery_task_id'] = celery_task_id.get()
    return True


fmt = "[<level>{level: <8}</level>] [devops] <green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> [<red>{x_trace_id}</red>] [<red>{celery_task_id}</red>] [<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan>] - <level>{message}</level>"

# 日志简单配置
logger.remove()
logger.add(sys.stdout, format=fmt, filter=correlation_id_filter, enqueue=True)
logger.add(log_file, format=fmt, filter=correlation_id_filter, rotation="00:00", retention="30 days", enqueue=True)

__all__ = ["logger"]
